package com.googlecode.aleverr.yafotkiclient.ui.activities;

import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.Toast;
import android.widget.ViewSwitcher;
import com.googlecode.aleverr.yafotkiclient.R;
import com.googlecode.aleverr.yafotkiclient.api.GlobalSettings;
import com.googlecode.aleverr.yafotkiclient.api.Photo;
import com.googlecode.aleverr.yafotkiclient.api.PhotoCollection;
import com.googlecode.aleverr.yafotkiclient.ui.adapters.PhotoGridAdapter;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

public class PhotoGridActivity extends Activity implements AdapterView.OnItemClickListener {

    private static final String TAG = "PhotoGridActivity";

    private final PhotoGridAdapter adapter = new PhotoGridAdapter();
    private String photoCollectionAddress;
    private String albumId;

    private static final int PROGRESS_BAR_INDEX = 0;
    private static final int GRID_VIEW_INDEX = 1;

    private static final int CAMERA_REQUEST = 0;
    private static final int UPLOAD_REQUEST = 1;

    private File lastImageFile;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.photo_grid);

        GridView gridView = (GridView) findViewById(R.id.gridview);
        gridView.setAdapter(adapter);
        gridView.setOnItemClickListener(this);

        Intent intent = getIntent();
        photoCollectionAddress = intent.getStringExtra("photoCollectionAddress");
        albumId = intent.getStringExtra("albumId");

        new LoadPhotosTask().execute();
    }

    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
        Photo photo = adapter.getItem(i);
        if (photo != null) {
            Intent intent = new Intent(this, PhotoViewerActivity.class);
            intent.putExtra("photo", photo);
            startActivity(intent);
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.photo_grid_menu, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.takePhoto:
                takePhoto();
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }

    private boolean takePhoto() {
        PackageManager packageManager = getPackageManager();
        if (!packageManager.hasSystemFeature(PackageManager.FEATURE_CAMERA)) {
            return false;
        }
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        List<ResolveInfo> list = packageManager.queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY);
        if (list.size() == 0) {
            return false;
        }
        try {
            File tmpStoreDir = new File(Environment.getExternalStorageDirectory().getAbsolutePath(), "YaFotkiClient");
            tmpStoreDir.mkdirs();
            String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
            lastImageFile = File.createTempFile(timeStamp, ".jpg", tmpStoreDir);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(lastImageFile));
            startActivityForResult(intent, CAMERA_REQUEST);
        } catch (IOException e) {
            Log.e(TAG, e.getMessage(), e);
        }
        return true;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case CAMERA_REQUEST:
                    if (lastImageFile != null) {
                        Intent intent = new Intent(this, UploadPhotoActivity.class);
                        intent.putExtra("filePath", lastImageFile.getAbsolutePath());
                        intent.putExtra("albumId", albumId);
                        startActivityForResult(intent, UPLOAD_REQUEST);

                        lastImageFile = null;
                    }
                    break;
                case UPLOAD_REQUEST:
                    boolean isUploaded = data.getBooleanExtra("uploaded", false);
                    if (isUploaded) {
                        Toast.makeText(this, "Photo was successfully uploaded", Toast.LENGTH_SHORT).show();
                        new LoadPhotosTask().execute();
                    } else {
                        Toast.makeText(this, "Error uploading photo", Toast.LENGTH_SHORT).show();
                    }
            }
        }
    }

    private class LoadPhotosTask extends AsyncTask<Void, Void, PhotoCollection> {

        @Override
        protected PhotoCollection doInBackground(Void... voids) {
            String accessToken = GlobalSettings.getInstance(PhotoGridActivity.this).getAccessToken();
            return PhotoCollection.fromUrl(photoCollectionAddress, accessToken);
        }

        @Override
        protected void onPreExecute() {
            ViewSwitcher viewSwitcher = (ViewSwitcher) findViewById(R.id.viewSwitcher);
            viewSwitcher.setDisplayedChild(PROGRESS_BAR_INDEX);
        }

        @Override
        protected void onPostExecute(PhotoCollection photoCollection) {
            adapter.update(photoCollection.getEntries());

            ViewSwitcher viewSwitcher = (ViewSwitcher) findViewById(R.id.viewSwitcher);
            viewSwitcher.setDisplayedChild(GRID_VIEW_INDEX);
        }
    }
}